﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;

namespace ComicIsland.App.Views
{
    public partial class ComicFeedbackPage : PhoneApplicationPage
    {
        public ComicFeedbackPage()
        {
            InitializeComponent();
            this.txtFeedbackContent.Text = AppResources.FeedbackContent;
            this.txtFeedbackMobile.Text = AppResources.FeedBackMobile;
            this.txtFeedbackQQ.Text = AppResources.FeedbackQQ;
            //
            this.psbStatus.CloseStatusBar();
        }

        private void appBarSubmit_Click(object sender, EventArgs e)
        {
            string content = this.txtFeedbackContent.Text.Trim();
            string qq = this.txtFeedbackQQ.Text.Trim();
            string mobile = this.txtFeedbackMobile.Text.Trim();
            //
            if (string.IsNullOrWhiteSpace(qq) && string.IsNullOrWhiteSpace(mobile))
            {
                MessageToastManager.Show(string.Concat(AppResources.FeedbackQQ, "或", AppResources.FeedBackMobile, "必须填写一项！"));
                return;
            }
            if (AppResources.FeedbackQQ.Equals(qq) && AppResources.FeedBackMobile.Equals(mobile))
            {
                MessageToastManager.Show(string.Concat(AppResources.FeedbackQQ, "或", AppResources.FeedBackMobile, "必须填写一项！"));
                return;
            }
            if (string.IsNullOrWhiteSpace(content) || AppResources.FeedbackContent.Equals(content))
            {
                MessageToastManager.Show(string.Concat(AppResources.FeedbackContent, "，必须填写！"));
                return;
            }
            string extContent = string.Format("|||SDKVersion:{0}|||RAMTotalSize:{1}MB|||RAMAvailSize:{2}MB", System.Environment.Version.ToString(), (DeviceStatus.DeviceTotalMemory / (1024 * 1024)), (DeviceStatus.ApplicationMemoryUsageLimit / (1024 * 1024)));
            content += extContent;
            this.AddFeedback(content, qq, mobile);

        }

        void AddFeedback(string content, string qq, string mobile)
        {
            //http://mhjk.1391.com/comic/addfeedback?e=1419927479
            //{"content":"相当不错|||SDKVersion:17|||RAMTotalSize:971MB|||RAMAvailSize:164 MB","qq":"881985678","version":"2.5.60","mobile":""}
            (this.ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/addfeedback", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("content", content);
            parameters.Add("mobile", mobile);
            parameters.Add("qq", qq);
            parameters.Add("version", KEYS.STORE_VERSION);
            parameters.Add("feedtype", ((int)KEYS.SearchWantComicFeedType.Question).ToString());

            PostClientHelper proxy = new PostClientHelper(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        return;
                    }

                    #region 获取结果处理
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        LogHelper.LogError("Result is empty.");
                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                        return;
                    }

                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                    //
                    bool submitResultStatus = false;
                    JObject jo = JObject.Parse(result);
                    if (jo != null)
                    {
                        JToken jt = jo["code"];
                        if (jt != null)
                        {
                            if (KEYS.JSON_SUCCESS.ToString().Equals(jt.ToString()))
                            {
                                submitResultStatus = true;
                            }
                        }
                    }
                    if (submitResultStatus)
                    {
                        MessageToastManager.Show("提交成功！");
                        if (this.NavigationService.CanGoBack)
                        {
                            this.NavigationService.GoBack();
                        }
                    }
                    else
                    {
                        MessageToastManager.Show("提交失败，请重试！");
                    }

                    #endregion 获取结果处理
                }
                finally
                {
                    (this.ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = true;
                    this.psbStatus.CloseStatusBar();
                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }

        private void txtFeedbackQQ_GotFocus(object sender, RoutedEventArgs e)
        {
            if (AppResources.FeedbackQQ.Equals(this.txtFeedbackQQ.Text.Trim()))
            {
                this.txtFeedbackQQ.Text = string.Empty;
            }
        }

        private void txtFeedbackQQ_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtFeedbackQQ.Text.Trim()))
            {
                this.txtFeedbackQQ.Text = AppResources.FeedbackQQ;
            }
        }

        private void txtFeedbackMobile_GotFocus(object sender, RoutedEventArgs e)
        {
            if (AppResources.FeedBackMobile.Equals(this.txtFeedbackMobile.Text.Trim()))
            {
                this.txtFeedbackMobile.Text = string.Empty;
            }
        }

        private void txtFeedbackMobile_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtFeedbackMobile.Text.Trim()))
            {
                this.txtFeedbackMobile.Text = AppResources.FeedBackMobile;
            }
        }

        private void txtFeedbackContent_GotFocus(object sender, RoutedEventArgs e)
        {
            if (AppResources.FeedbackContent.Equals(this.txtFeedbackContent.Text.Trim()))
            {
                this.txtFeedbackContent.Text = string.Empty;
            }
        }

        private void txtFeedbackContent_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtFeedbackContent.Text.Trim()))
            {
                this.txtFeedbackContent.Text = AppResources.FeedbackContent;
            }
        }
    }
}